﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.Collections.Specialized;
using Facebook.Json;
using System.Collections.Generic;

namespace Facebook.Web.Mvc
{
    public class FeedController : FacebookMvcController
    {
        public ActionResult PostFbml(String id)
        {
            var ids = Facebook.Configuration.FeedTemplateBundleIds.GetCurrent(this.FbContext.ApiKey);
            var templateId = ids.Single(tid => tid.Name == id);

            var result = this.Json(new
            {
                content = new
                {
                    feed = new
                    {
                        template_id = templateId.Id,
                        template_data = this.GetTemplateData()
                    }
                },
                method = "feedStory"
            });

            return result;
        }

        public ActionResult PostIFrame(String id)
        {
            var ids = Facebook.Configuration.FeedTemplateBundleIds.GetCurrent(this.FbContext.ApiKey);
            var templateId = ids.Single(tid => tid.Name == id);
            var templateData = this.GetTemplateData();

            var output = new StringBuilder(String.Format("FB.Connect.showFeedDialog({0}", templateId.Id));
            if (templateData.Count > 0) output.AppendFormat(",{0}", JsonConvert.SerializeObject(templateData));
            output.Append(");");

            return this.JavaScript(output.ToString());
        }

        private IDictionary<String, String> GetTemplateData()
        {
            return (
                from paramKey in this.Request.Params.Keys.OfType<String>()
                where paramKey.StartsWith("__fb_feed_")
                select new { Name = paramKey.Replace("__fb_feed_", String.Empty), Value = this.Request.Params[paramKey] })
                    .ToDictionary(data => data.Name, data => data.Value);
        }
    }
}